//
//  YZFetterDetailController.swift
//  YZFetter
//
//  Created by 康凯 on 2017/7/13.
//  Copyright © 2017年 康凯. All rights reserved.
//

import UIKit
import CoreBluetooth
import RxSwift
import PKHUD

enum FetterHandle: Int{         // 操作类型
    case selfTest               // 系统自检
    case signalStrength         // 信号检测
    case openFetter             // 开锁
    case closeFetter            // 关锁
    case blueConfig             // 配置
    case getFetterInfo          // 获取状态
    case other
}

enum FFF3Handle: Int {             // 写FFF3的类型
    case none                      // 保留位
    case rtc_calibrating  = 1      // 同步时钟
    case moto_pwron                // 开锁
    case moto_pwroff               // 关锁
    case self_test                 // 系统自检
    case gsmStat                   // 信号检测
}

let itemHeight: CGFloat =  40.0
let buttonSep: CGFloat = 10
let buttonWidth: CGFloat = (kScreen_Width - 4 * buttonSep) / 3
private var statusCodeContext = 1

class YZFetterDetailController: KBaseViewController {

    let bag = DisposeBag()
    let blueToothManager: YZBlueToothManager = YZBlueToothManager.shareInstances        // 蓝牙管理对象
    var characteristics: [CBCharacteristic] = []                // 特征列表
    var peripheralMacAddress: Data!                             // 设备的Mac地址
    var peripheralName: String!                                 // 蓝牙名称
    var rightBtn: UIBarButtonItem!                              // 重连按钮
    var isPushed: Bool = true                                   // 判断是不是重连
    
    fileprivate var dataSource: [[(String, String)]] = []       // tableView数据源
    fileprivate var statusMessage: UILabel!                     // 显示状态信息
    let statuCode = Variable<Int>(0)                            // 状态码
    var currentHandle = Variable<FetterHandle>(.other)          // 当前操作类型
    
    var TL1: Int = 0        // TL1 0为关闭状态
    var TL2: Int = 0        // TL2 0为开启状态

    var SX:  Int = 0        // 锁舌状态
    
    var FN: Int = 0         // 故障代码
    var WV: Int = 0         // 信号强度
    
    var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        subViewInit()
        subscribeChara()
    }
    
    // MARK:- Life Cycle
    override func viewWillAppear(_ animated: Bool) {
        isPushed = true
        getFetterInfo()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        isPushed = true
    }
    
    override func viewDidDisappear(_ animated: Bool) {
    
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    override func backAction(item: UIBarButtonItem) {
        
        blueToothManager.cancelConnect()
        NotificationCenter.default.removeObserver(self)
        super.backAction(item: item)
    }

    // 初始化子控件
    func subViewInit() {
        
        title = "设备详情"
        view.backgroundColor = UIColor.init(rgbHex: "ededed")
        self.navigationItem.leftBarButtonItem?.tintColor = themeColor
        
        rightBtn = UIBarButtonItem.init(barButtonSystemItem: .refresh, target: self, action: #selector(YZFetterDetailController.autoConnect))
        rightBtn.tintColor = themeColor
        rightBtn.isEnabled = false
        navigationItem.rightBarButtonItem = rightBtn
        
        // 订阅断开连接的通知
        NotificationCenter.default.addObserver(self, selector: #selector(YZFetterDetailController.disConnect), name: NSNotification.Name(rawValue: peripherDisConnected), object: nil)
        
        tableView = UITableView.init(frame: CGRect.zero, style: .plain)
        tableView.backgroundColor = UIColor.white
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorColor = UIColor.clear
        tableView.bounces = false
        tableView.register(YZFetterDetailItemCell.classForCoder(), forCellReuseIdentifier: NSStringFromClass(YZFetterDetailItemCell.self))
        view.addSubview(tableView)
        tableView.snp.makeConstraints {
            $0.edges.equalTo(self.view).inset(UIEdgeInsetsMake(0, 0, 128, 0))
        }
        
        statusMessage = UILabel()
        statusMessage.frame = CGRect.init(x: 0, y: kScreen_Height - 128, width: kScreen_Width, height: 40)
        statusMessage.backgroundColor = UIColor.white
        statusMessage.font = UIFont.systemFont(ofSize: is_iPhone_5_orLess ? 15 : 16 + 1)
        statusMessage.textAlignment = .center
        setMessage(color: themeColor, message: "设备已连接，可操作")
        view.addSubview(statusMessage)
        
        for i in 0..<6 {
            let operatBtn = UIButton.init()
            operatBtn.frame = CGRect.init(x: CGFloat(i % 3) * (buttonSep + buttonWidth) + buttonSep,
                                            y: kScreen_Height - 88 + CGFloat(i / 3) * (35 + 6) + 6,
                                            width: buttonWidth,
                                            height: 35)
            operatBtn.backgroundColor = themeColor
            operatBtn.layer.cornerRadius = 5
            operatBtn.titleLabel?.font = k_labelFont
            operatBtn.setTitle(["配置", "自检", "信号强度", "查询", "关锁", "开锁"][i], for: .normal)
            operatBtn.tag = i + 1
            operatBtn.addTarget(self, action: #selector(YZFetterDetailController.action(for:)), for: .touchUpInside)
            view.addSubview(operatBtn)
        }
        
        // 状态订阅
        subscribeStatus()
        
        _ = statuCode.asObservable().subscribe(onNext: {
            [weak self] statusCode in
            if statusCode > 0 {             // 状态更新后
                self?.getFetterInfo()       // 取设备状态
            }
        })
        
        blueToothManager.peripheralList.asObservable().subscribe(onNext: {
            [weak self] peripherals in
            
            if !(self?.isPushed)! {
                for peripheral in peripherals {
                    if peripheral.name == self?.peripheralName {
                        self?.blueToothManager.connect(to: peripheral)
                    }
                }
            }
        }).addDisposableTo(bag)
        
        _ = blueToothManager.characteristicList.asObserver().subscribe (onNext: { [weak self] characteristics in
            guard characteristics.count != 0 else {
                return
            }
            
            if !(self?.isPushed)! {
                if characteristics[0].service.uuid == CBUUID.init(string: customerServiceUUID) {
                    self?.rightBtn.isEnabled = false
                    self?.characteristics = characteristics
                    self?.setMessage(color: themeColor, message: "设备已连接，可操作")
                    self?.subscribeStatus()
                    self?.getFetterInfo()
                }
            }
        }).addDisposableTo(bag)
        
        _ = currentHandle.asObservable().subscribe(onNext: {
            [weak self] nowHandle in
            switch nowHandle {
            case .closeFetter:
                self?.settingFFF3(num: FFF3Handle.moto_pwroff.rawValue)
            case .openFetter:
                self?.settingFFF3(num: FFF3Handle.moto_pwron.rawValue)
            case .selfTest:
                HUD.show(.progress)
                self?.settingFFF3(num: FFF3Handle.self_test.rawValue)
                self?.setMessage(color: UIColor.red, message: "勿动！自检测试中")
            case .signalStrength:
                HUD.show(.progress)
                self?.settingFFF3(num: FFF3Handle.gsmStat.rawValue)
                self?.setMessage(color: UIColor.red, message: "勿动！信号强度测试中")
            case .blueConfig:
                self?.jumpToFetterConfig()
            case .getFetterInfo:
                self?.getFetterInfo()
                self?.setMessage(color: themeColor, message: "状态已刷新")
            default:
                break
            }
        })
        
        synchTime()
    }
    
    // 订阅status变化的消息
    func subscribeStatus() {
        if characteristics[3].uuid.uuidString == "FFF4" {
            blueToothManager.subscribe(for: characteristics[3])
        }
    }
    
    // 订阅blueToothManager的消息，用于设置数据源
    func subscribeChara() {
        _ = blueToothManager.characteristicValue.subscribe(onNext: { characteristic in
            switch characteristic.uuid.uuidString {
            case "FFF1":
                let deviceInfo = YZFetterParseModel.decodeCharaFFF1(for: characteristic.value!)
                guard deviceInfo.0.count > 0 else { return }
                
                var deviceInfoDataSource: [(String, String)] = []
                for (index, value) in deviceInfo.0.enumerated(){
                    deviceInfoDataSource.append((value, deviceInfo.1[index]))
                }
                self.dataSource.append(deviceInfoDataSource)
                
            case "FFF4":
                self.statuCode.value = Int(characteristic.value![0])
                
            case "FFF5":
                let deviceStatu = YZFetterParseModel.decodeCharaFFF5(for: characteristic.value!)
                guard deviceStatu.0.count > 0 else { return }
                
                var deviceStatuDataSource: [(String, String)] = []
                for (index, value) in deviceStatu.0.enumerated(){
                    if value == "锁舌状态" {
                        let sx = deviceStatu.1[index] as NSString
                        self.SX = Int(sx.substring(to: 1))!
                    }else if value == "锁销状态" {
                        let tl = deviceStatu.1[index] as NSString
                        self.TL1 = Int(tl.substring(to: 1))!
                        self.TL2 = Int(tl.substring(with: NSRange.init(location: 2, length: 1)))!
                    }else if value == "故障代码" {
                        self.FN = Int(deviceStatu.1[index])!
                    }else if value == "无线网络信号" {
                        self.WV = Int(deviceStatu.1[index])!
                    }
                    
                    deviceStatuDataSource.append((value, deviceStatu.1[index]))
                }
                self.dataSource.insert(deviceStatuDataSource, at: 0)
                if (self.dataSource.count == 2) {
                    self.tableView.reloadData()
                    self.setStatusMessage()    // 在更改statusMessage的值
                }
            default:
                print("defaule")
            }
        }).addDisposableTo(bag)
    }
    
    // MARK:- Customer Func
    // 点击按钮的事件
    func action(for button: UIButton) {
        if blueToothManager.checkBlueState() && blueToothManager.checkConnectStatus() {
            switch button.tag {
            case 1:             // 配置
                currentHandle.value = .blueConfig
            case 2:             // 自检
                currentHandle.value = .selfTest
            case 3:             // 信号强度
                currentHandle.value = .signalStrength
            case 4:             // 查询
                currentHandle.value = .getFetterInfo
            case 5:             // 关锁
                currentHandle.value = .closeFetter
            case 6:             // 开锁
                currentHandle.value = .openFetter
            default:
                break
            }
        }else {
            
        }
    }
    
    // 读取特征值FFF3 和 FFF5的值
    // 设备信息和设备状态
    func getFetterInfo() {
        dataSource.removeAll()
        for chara in characteristics {
            if chara.uuid.uuidString == "FFF5" || chara.uuid.uuidString == "FFF1" {
                blueToothManager.readValue(for: chara)
            }
        }
    }
    
    // 设置statusMessage
    func setStatusMessage() {
        switch self.currentHandle.value {
        case .openFetter:
            
            if TL1 == TL2 && TL1 == 1 {
                setMessage(color: themeColor, message: "锁销未到位，请重新操作")
            }else if SX == 0, TL1 == 1, TL2 == 0 {
                setMessage(color: themeColor, message: "锁销已开启，请旋转锁芯")
            }else if SX == 1, TL1 == 0, TL2 == 1 {
                setMessage(color: themeColor, message: "锁已开启")
            }else if SX == 0, TL1 == 0, TL2 == 1 {
                setMessage(color: themeColor, message: "锁已关闭")
            }else {
                setMessage(color: themeColor, message: String.init(format: "锁异常SX=%d，TL1=%d，TL2=%d", SX,TL1,TL2))
            }
        case .closeFetter:
            setMessage(color: themeColor, message: "锁已关闭")
        case .selfTest:
            if FN == 0 {
                setMessage(color: themeColor, message: "自检无故障")
            }else {
                setMessage(color: themeColor, message: "自检完成，故障代码：\(FN)")
            }
        case .signalStrength:
            if statuCode.value == 1 {
                setMessage(color: themeColor, message: "信号强度测试完成，信号强度：\(WV)")
            } else {
                setMessage(color: themeColor, message: "信号强度测试失败")
            }
        case .getFetterInfo:
            break
        default:
            break
        }
    }
    
    // 自动连接
    func autoConnect()  {
        // 刷新蓝牙列表
        HUD.show(.labeledProgress(title: "", subtitle: "正在扫描，请确保设备已激活"))
        blueToothManager.refreshBT()
    }
    
    // 设置状态信息
    func setMessage(color textColor: UIColor, message msg: String) {
        self.statusMessage.textColor = textColor
        self.statusMessage.text = msg
    }
    
    // 同步时钟
    func synchTime()  {
        let currentDate = Date.init(timeIntervalSinceNow: 0)
        let dateformatter = DateFormatter()
        dateformatter.dateFormat = "YYYY.MM.dd.HH.mm.ss"
        let currentTime = dateformatter.string(from: currentDate)
        let timeArr = currentTime.components(separatedBy: ".")
        
        var byte: [UInt8] = Array.init(repeating: UInt8(00), count: 20)
        byte[0] = UInt8(01)
        byte[1] = UInt8((Int(timeArr[0])! % 10000) / 100)
        byte[2] = UInt8(Int(timeArr[0])! % 100)
        byte[3] = UInt8(timeArr[1])!
        byte[4] = UInt8(timeArr[2])!
        byte[5] = UInt8(timeArr[3])!
        byte[6] = UInt8(timeArr[4])!
        byte[7] = UInt8(timeArr[5])!
        
        blueToothManager.write(data: Data.init(bytes: byte), for: characteristics[2])
    }
    
    // 针对FFF2的操作
    func settingFFF3(num: Int) {
        if characteristics[2].properties == .write {
            var byte: [UInt8] = Array.init(repeating: UInt8(00), count: 20)
            byte[0] = UInt8(num)
            blueToothManager.write(data: Data.init(bytes: byte), for: characteristics[2])
        }
    }
    
    // 跳转到配置界面
    func jumpToFetterConfig() {
        let fetterConfigVC = YZFetterConfigViewController()
        fetterConfigVC.number = dataSource[1][0].1   // 卡号
        fetterConfigVC.SMS = dataSource[1][3].1         // 告警号码，短信号码
        fetterConfigVC.ip  = dataSource[1][1].1         // IP地址
        fetterConfigVC.port = dataSource[1][2].1         // 端口号
        fetterConfigVC.wakeInterval = dataSource[1][5].1    // 自动唤醒时长
        fetterConfigVC.modeNum = dataSource[1][4].1         // 通信模式
        if  characteristics[0].uuid.uuidString == "FFF1" {
            fetterConfigVC.configCharacteristic = characteristics[0]
        }
        
        self.navigationController?.pushViewController(fetterConfigVC, animated: true)
    }
    
    // 连接已断开
    func disConnect() {
        rightBtn.isEnabled = true
        isPushed = false
        HUD.hide()
        let alertVC = UIAlertController.init(title: "错误", message: "连接已断开，点击重连按钮重新连接设备", preferredStyle: .alert)
        alertVC.addAction(UIAlertAction.init(title: "好的", style: .default, handler: { (alertAction) in
            self.setMessage(color: UIColor.red, message: "连接已断开，点击重连按钮重新连接设备")
        }))
        self.present(alertVC, animated: true, completion: nil)
    }
}

// MARK:- UITableViewDataSource
extension YZFetterDetailController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(YZFetterDetailItemCell.self), for: indexPath) as! YZFetterDetailItemCell
        
        if self.dataSource.count != 0 {
            cell.title = dataSource[indexPath.section][indexPath.row].0
            cell.detail = dataSource[indexPath.section][indexPath.row].1
        }
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let label = UILabel.init()
        label.backgroundColor = UIColor.init(rgbHex: "ededed")
        label.textColor = UIColor.init(rgbHex: "959599")
        label.font = k_labelFont
        label.text = ["  锁状态", "  锁信息"][section]
        return label
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return itemHeight
    }
}

// MARK:- UITableViewDelegate
extension YZFetterDetailController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return itemHeight
    }
}
